import {Injectable} from '@nestjs/common'
const request = require('request')
const COS = require('cos-nodejs-sdk-v5');
import { cosConfig } from '../config/cos.config'
import * as STS  from 'qcloud-cos-sts';
// import {WxService} from '../app/wx/wx.service';

@Injectable()
export class Utils {
    private KEY:String = "D47BZ-VYVWQ-NNO5S-GLWIV-3USFJ-ZIBBN";

    constructor(
        // private readonly wxService:WxService,
    ) {}

    /**
     * @description: 通过经纬度获取地理位置
     * @param {number} lng
     * @param {number} lat
     * @return: Map 省市区
     */
    public async getLocation(lng:number, lat:number):Promise<Map<string, string>> {
        const urlString:string = "http://apis.map.qq.com/ws/geocoder/v1/?location=" + lat + "," + lng + "&key=" + this.KEY + "&get_poi=1";
        const result: any = await this.getLocationRequest(urlString);
        const jsonObject = JSON.parse(result)['result']['ad_info'];
        let resultMap:Map<string, string> = new Map();
        resultMap.set('province',jsonObject.nation);
        resultMap.set('city',jsonObject.city);
        resultMap.set('area',jsonObject.district);
        return resultMap;
    }
    /**
     * @description: request请求
     * @param {type} 
     * @return: 
     */
    public getLocationRequest(url:string):Promise<string>{
        return new Promise(function(resolv,reject){
            request(url, (err,res,body)=>{
                resolv(body);
            })
        });
    }

    /**
     * @description: 上传图片
     * @param {buffer}  文件流
     * @return: 
     */
    public async upload(bufferFile:Buffer,filePath:string):Promise<any>{
        return new Promise(async (resolve,reject)=>{
            let cosData:any = await this.getStsAuto();
            cosData = JSON.parse(cosData);
            const credentials = cosData.credentials;
            var cos = new COS({
                getAuthorization: function (options, callback) {
                    callback({
                        TmpSecretId: credentials.tmpSecretId,
                        TmpSecretKey: credentials.tmpSecretKey,
                        XCosSecurityToken: credentials.sessionToken,
                        ExpiredTime: cosData.expiredTime,
                    });
                }
            });
            cos.putObject({
                Bucket: 'yanghujinyuan-1252409825',
                Region: 'ap-guangzhou',
                Key: filePath,
                Body: bufferFile, // 这里传入前缀
            }, function (err, data) {
                resolve(`https://${data.Location}`)
            });
        })
    }
    public getRad(d){
        return d*Math.PI/180.0;
    }

    public getGreatCircleDistance(lat1:number,lng1:number,lat2:number,lng2:number):number{
        var radLat1 = this.getRad(lat1);
        var radLat2 = this.getRad(lat2);
        var a = radLat1 - radLat2;
        var b = this.getRad(lng1) - this.getRad(lng2);
        var s = 2*Math.asin(Math.sqrt(Math.pow(Math.sin(a/2),2) + Math.cos(radLat1)*Math.cos(radLat2)*Math.pow(Math.sin(b/2),2)));
        s = s*6378137.0;
        s = Math.round(s*10000)/10000.0;
        return s;
    }

    public async getStsAuto():Promise<object>{
        // 获取临时密钥
        var LongBucketName = cosConfig.bucket;
        var ShortBucketName = LongBucketName.substr(0, LongBucketName.indexOf('-'));
        var AppId = LongBucketName.substr(LongBucketName.indexOf('-') + 1);
        var policy = {
            'version': '2.0',
            'statement': [{
                "action": [
                    "cos:PostObject",
                    "cos:PutObject*",
                    "cos:InitiateMultipartUpload",
                    "cos:UploadPart",
                    "cos:CompleteMultipartUpload",
                    "cos:AbortMultipartUpload"
                ],
                'effect': 'allow',
                'principal': {'qcs': ['*']},
                'resource': '*',
            }],
        };
        const _result:any = await this.getSTS(policy);
        return _result
    }

    private getSTS(policy){
        return new Promise((resolve,reject)=>{
            STS.getCredential({
                secretId: cosConfig.secretId,
                secretKey: cosConfig.secretKey,
                proxy: cosConfig.proxy,
                durationSeconds: cosConfig.durationSeconds,
                policy: policy,
            }, function (err, tempKeys) {
                var result:any = JSON.stringify(err || tempKeys) || '';
                resolve(result)
            });
        }) 
    }
}


// import * as Excel from 'exceljs';
// import { Injectable,Controller } from '@nestjs/common';
// import * as fs from 'fs';
// @Injectable()
// export class exportdata{
//     unlink(){
//         fs.unlink('./用户报表.xlsx', async err=> {
//             Promise.resolve()
//         })
//     }
//     async getEcsel(data:any):Promise<number> {
//         const workbook = new Excel.Workbook()
//         workbook.creator = 'test'
//         workbook.lastModifiedBy = 'test'
//         workbook.created = new Date()
//         workbook.modified = new Date()
//         let sheet = workbook.addWorksheet('2018-10报表');
//         sheet.columns = [
//             {header: '区域', key: 'region', width: 15},
//             {header: '地址', key: 'address', width: 15},
//             {header: '商家名称', key: 'b_name', width: 15},
//             {header: '业态', key: 'b_type', width: 15},
//             {header: '细分', key: 'subdivide', width: 15},
//             {header: '意向', key: 'intention', width: 15},
//             {header: '电话/微信', key: 'phone', width: 15},
//             {header: '商家级别', key: 'b_level', width: 15},
//             {header: '备注', key: 'remark', width: 15}
//         ]
//         sheet.addRows(data);
//         try {
//             await this.unlink();
//             await workbook.xlsx.writeFile('./用户报表.xlsx')
//             return await Promise.resolve(1);
//         } catch (error) {
//             return await Promise.resolve(2);
//         }
//     }
// }

// export function getRandomInt(min, max) {
//     min = Math.ceil(min);
//     max = Math.floor(max);
//     return Math.floor(Math.random() * (max - min)) + min;
// }